package routes

import (
	"mygame/app/controller"
	"mygame/app/middleware"
	mywebsocket "mygame/app/websocket"
	"mygame/pkg/logger"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func Router() *gin.Engine {
	router := gin.Default()

	// 初始化 websocket
	// initWs(router)

	// 配置 CORS 中间件
	initCors(router)

	router.Use(gin.LoggerWithConfig(logger.LoggerToFile()))
	router.Use(logger.Recover)

	// 添加全局错误处理中间件（最后注册，确保捕获所有后续错误）
	router.Use(middleware.ErrorHandleMiddleware())

	{
		router.GET("/test", controller.Test{}.Test)
		router.POST("/t2", controller.Test{}.T2)
		router.POST("/login", controller.User{}.Login)
		router.POST("/wxLogin", controller.User{}.WxLogin)
	}

	authorized := router.Group("/", middleware.AuthMiddleware())
	{
		authorized.GET("user", controller.User{}.Info)
		authorized.POST("user/syncData", controller.User{}.SyncData)
		authorized.GET("user/getData", controller.User{}.GetData)
	}

	return router
}

func initWs(r *gin.Engine) {
	manager := mywebsocket.NewManager()
	// manager := mywebsocket.NewManager(redispkg.Rdb)
	broadcaster := mywebsocket.NewBroadcaster(manager)
	healthcheck := mywebsocket.NewHealthChecker(manager)

	// 注入中间件
	r.Use(manager.Middleware())

	// 注册路由
	r.GET("/ws", mywebsocket.HandleWebSocket)
	r.POST("/broadcast", broadcaster.BroadcastHandler)

	// 启动心跳检测，发送ping
	healthcheck.Start()

	// 健康检查端点
	r.GET("/health", func(c *gin.Context) {
		count := 0
		manager.Connections.Range(func(_, _ interface{}) bool {
			count++
			return true
		})
		c.JSON(200, gin.H{"connections": count})
	})
}

func initCors(router *gin.Engine) {
	router.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},                                       // 允许所有来源
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允许方法
		AllowHeaders:     []string{"*"},                                       // 允许头
		ExposeHeaders:    []string{"Content-Length"},                          // 暴露头
		AllowCredentials: true,                                                // 允许凭证
		MaxAge:           12 * time.Hour,                                      // 预检结果缓存时间
	}))
}
